package com.loe.ktui.util

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

class KtGridDecoration constructor(var pL: Int = 0, var pT: Int = 0, var pR: Int = 0, var pB: Int = 0, var count: Int = 2, var space: Int = 0, var startSize: Int = 0) : RecyclerView.ItemDecoration()
{
    /**
     * 尾部 不显示间距的item个数 默认不处理最后一个item的间距
     */
    private var endSize = 0

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State)
    {
        val lastPosition = state.itemCount - 1
        var position = parent.getChildAdapterPosition(view)

        val spaceHalf = space / 2

        if (startSize <= position && position <= lastPosition - endSize)
        {
            // 减掉不设置间距的position
            position -= startSize
            var column = position % count

            // 瀑布流获取列方式不一样
            val layoutParams = view.layoutParams
            if (layoutParams is StaggeredGridLayoutManager.LayoutParams)
            {
                column = layoutParams.spanIndex
            }

            if (column == 0)
            {
                outRect.left = pL
            } else
            {
                outRect.left = spaceHalf
            }
            if (column == count - 1)
            {
                outRect.right = pR
            } else
            {
                outRect.right = spaceHalf
            }

            if (position < count)
            {
                outRect.top = pT
            } else
            {
                outRect.top = space
            }
            if (position >= state.itemCount - count)
            {
                outRect.bottom = pB
            }
        }
    }

    fun setPH(p: Int): KtGridDecoration
    {
        pL = p
        pR = p
        return this
    }

    fun setPV(p: Int): KtGridDecoration
    {
        pT = p
        pB = p
        return this
    }

    /**
     * 设置从哪个位置 开始设置间距
     *
     * @param startSize 一般为HeaderView的个数 + 刷新布局(不一定设置)
     */
    fun setStartSize(startSize: Int): KtGridDecoration
    {
        this.startSize = startSize
        return this
    }

    /**
     * 设置从哪个位置 结束设置间距。默认为1，默认用户设置了上拉加载
     *
     * @param endSize 一般为FooterView的个数 + 加载更多布局(不一定设置)
     */
    fun setEndSize(endSize: Int): KtGridDecoration
    {
        this.endSize = endSize
        return this
    }

    /**
     * 设置从哪个位置 结束设置间距
     *
     * @param startSize 一般为HeaderView的个数 + 刷新布局(不一定设置)
     * @param endSize   默认为1，一般为FooterView的个数 + 加载更多布局(不一定设置)
     */
    fun setRange(startSize: Int, endSize: Int): KtGridDecoration
    {
        this.startSize = startSize
        this.endSize = endSize
        return this
    }
}